<template>
  <a-modal v-model:visible="visible" centered title="修改密码" :footer="null">
    <a-form ref="passwordRef" :model="passwordModelForm" @finish="handleFinish">
      <a-form-item
        label="旧密码"
        :label-col="labelCol"
        name="oldPassword"
        :rules="rulesRef.oldPassword"
      >
        <a-input-password
          v-model:value="passwordModelForm.oldPassword"
          placeholder="请输入旧密码"
        />
      </a-form-item>
      <a-form-item
        label="新密码"
        :label-col="labelCol"
        name="newPassword"
        :rules="rulesRef.newPassword"
      >
        <a-input-password
          v-model:value="passwordModelForm.newPassword"
          placeholder="请输入新密码"
        />
      </a-form-item>
      <a-space class="w-full justify-center">
        <a-button type="primary" html-type="submit"> 确认修改 </a-button>
      </a-space>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import { updateUserPassword } from '@/api/system/user';
  import { encryptByMd5 } from '@/utils/common';
  import { useUserStore } from '@/store/modules/user';

  const visible = ref(false);
  const updateData = reactive({
    passwordRef: null,
    passwordModelForm: {
      oldPassword: '',
      newPassword: '',
    },
    rulesRef: {
      oldPassword: [
        {
          required: true,
          message: '请输入旧密码',
        },
      ],
      newPassword: [
        {
          required: true,
          message: '请输入新密码',
        },
      ],
    },
    labelCol: { span: 6 },
  });
  const { passwordRef, passwordModelForm, rulesRef, labelCol } = toRefs(updateData);
  const handleFinish = async (values) => {
    const res = await updateUserPassword({
      oldPassword: encryptByMd5(values.oldPassword),
      password: encryptByMd5(values.newPassword),
    });
    if (res) {
      visible.value = false;
      message.success('修改密码成功!');
      await useUserStore().logout();
    }
  };
  defineExpose({ visible });
</script>

<style scoped></style>
